<template>
  <!-- 巡检计划 -->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="巡检计划" prop="planName">
        <el-input v-model="queryParams.planName" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="巡检点位" prop="title">
        <el-select multiple v-model="queryParams.medicineType" placeholder="请选择巡检点位" style="width: 100%">
          <el-option label="未完成" value="1"></el-option>
          <el-option label="已完成" value="2"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="barrelList" @selection-change="handleSelectionChange">
      <el-table-column label="巡检计划" align="center" prop="planName" />
      <el-table-column label="关联巡检点位" align="center" prop="inspectionSettings">
        <template slot-scope="scope">
          <div>
            <div :key="item.inspectionSettingId" v-for="item of scope.row.inspectionSettings">
              {{ item.inspectionName }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="巡检人员" align="center" prop="inspectionUserName" />
      <el-table-column label="巡检时间" align="center" prop="planData">
        <template slot-scope="scope">
          <div>
            <div v-if="scope.row.inspectionType == '按天'">
              每<span>{{ scope.row.planData }}</span>天，巡检一次，从该计划生效当天开始计算。
            </div>
            <div v-if="scope.row.inspectionType == '按周'">
              每周<span>{{ scope.row.planData }}</span>巡检。
            </div>
            <div v-if="scope.row.inspectionType == '按月'">
              每月<span>{{ scope.row.planData }}</span>号巡检。
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.iot_is_enable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handlePoint(scope.row)">管理巡检点位</el-button>
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改药桶编号对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="巡检计划" prop="planName">
          <el-input v-model="form.planName" placeholder="请输入巡检计划" />
        </el-form-item>
        <el-form-item label="巡检人员" prop="inspectionUserId">
          <el-select v-model="form.inspectionUserId" placeholder="请选择巡检人员" style="width: 100%">
            <el-option v-for="dict in userList" :key="dict.userId" :label="dict.userName"
              :value="dict.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="巡检时间">
          <div>
            <el-radio-group @change="groupChange" v-model="form.inspectionType">
              <el-radio-button label="按天"></el-radio-button>
              <el-radio-button label="按周"></el-radio-button>
              <el-radio-button label="按月"></el-radio-button>
            </el-radio-group>
            <div style="padding: 20px;">
              <div v-if="form.inspectionType == '按天'">
                <span>每</span>
                <el-input style="width:100px;margin: 0 5px;" v-model="form.planData" placeholder="请输入天数" />
                <span>天，巡检一次，从该计划生效当天开始计算。</span>
              </div>
              <div v-if="form.inspectionType == '按周'">
                <el-select multiple v-model="form.planData" placeholder="请选择" style="width: 100%">
                  <el-option v-for="dict in cities" :key="dict.vaule" :label="dict.label"
                    :value="dict.vaule"></el-option>
                </el-select>
              </div>
              <div v-if="form.inspectionType == '按月'">
                <div>
                  请勾选要巡检的日期：
                </div>
                <el-select multiple v-model="form.planData" placeholder="请选择" style="width: 100%">
                  <el-option v-for="dict in 31" :key="dict" :label="dict" :value="dict"></el-option>
                </el-select>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.iot_is_enable" :key="dict.value" :label="dict.value">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 管理巡检点位话框 -->
    <el-dialog title="巡检点位" :visible.sync="pointOpen" width="1000px" append-to-body>
      <div>
        <el-row>
          <el-col :span="16">
            <el-table :data="pointlist" @selection-change="pointlistChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="巡检点位名称" align="center" prop="inspectionName" />
              <el-table-column label="污水处理站点" align="center" prop="groupName" />
              <el-table-column label="关联设备" align="center" prop="deviceType">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.associated_devices" :value="scope.row.deviceType" />
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="poinParams.total > 0" :total="poinParams.total" :page.sync="poinParams.pageNum"
              :limit.sync="poinParams.pageSize" @pagination="getPoinList" />
          </el-col>
          <el-col :span="8">
            <div class="poin_warp">
              <div class="poin_header">已选点位</div>
              <div class="poin_center">
                <el-tag style="margin: 5px;" :key="index" v-for="(item, index) in dynamicTags" closable
                  @close="handleClose(item)">
                  {{ item.inspectionName }}
                </el-tag>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <div slot="footer" style="text-align: center;">
        <el-button type="primary" @click="submitpoint">确 定</el-button>
        <el-button @click="pointOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSetting } from "@/api/site/set";
import { listUser } from "@/api/system/user";
import { listPlan, getPlan, addPlan, updatePlan, delPlan, addIotPlan, getDevice } from "@/api/site/plan";
export default {
  name: "Barrel",
  dicts: ['iot_is_enable', 'sys_normal_disable', 'his_medicine_type', 'his_dept_status', 'associated_devices'],
  data() {
    return {
      pointOpen: false,
      cities: [
        {
          label: '周一',
          vaule: '1',
          checked: false
        },
        {
          label: '周二',
          vaule: '2',
          checked: false
        },
        {
          label: '周三',
          vaule: '3',
          checked: false
        },
        {
          label: '周四',
          vaule: '4',
          checked: false
        },
        {
          label: '周五',
          vaule: '5',
          checked: false
        },
        {
          label: '周六',
          vaule: '6',
          checked: false
        },
        {
          label: '周日',
          vaule: '7',
          checked: false
        }
      ],
      pageSizes: [6, 10, 20, 30, 50],
      qrWidth: 70,
      qrHeight: 70,
      qrContent: "",
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 药桶编号表格数据
      barrelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planName: null,
        sort: null,
        dataStatus: null,
      },
      // 表单参数
      form: {
        inspectionType: '按天'
      },
      // 表单校验
      rules: {
        inspectionUserId: [
          { required: true, message: "巡检人员不能为空", trigger: "blur" }
        ],
        planName: [
          { required: true, message: "巡检计划不能为空", trigger: "blur" }
        ],
        planName: [
          { required: true, message: "巡检计划不能为空", trigger: "blur" }
        ],
        planData: [
          { required: true, message: "巡检时间不能为空", trigger: "blur" }
        ]
      },
      pointlist: [],
      poinParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      dynamicTags: [],
      dynamicPoin: [],
      userList: [],
      inspectionPlanIditem: '',
      getDeviceData: [],
    };
  },
  created() {
    this.getList();
    this.getUserList();
  },
  methods: {
    /** 查询用户列表 */
    getUserList() {
      let params = {
        pageNum: 1,
        pageSize: 999,
      }
      listUser(params).then(response => {
        this.userList = response.rows;
      }
      );
    },
    groupChange(e) {
      if (e == '按天') {
        this.form.planData = undefined
      } else {
        this.form.planData = []
      }
    },
    /** 查询药桶编号列表 */
    getList() {
      this.loading = true;
      this.barrelList = []
      listPlan(this.queryParams).then(response => {
        this.barrelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        planName: null,
        inspectionUserId: [],
        inspectionType: '按天',
        planData: undefined,
        status: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inspectionPlanId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加巡检计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.inspectionPlanId || this.ids
      getPlan(id).then(response => {
        this.form = response.data;
        if (this.form.inspectionType == '按天') {
          this.form.planData = response.data.planData
        } else {
          this.form.planData = response.data.planData.split(',')
        }
        let arr = response.data.inspectionUserId.split(',')
        let arrUser = []
        for (let item of arr) {
          arrUser.push(item * 1)
        }
        this.form.inspectionUserId = arrUser
        this.open = true;
        this.title = "修改巡检计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.inspectionPlanId != null) {
            let params = {
              inspectionPlanId: this.form.inspectionPlanId,
              planName: this.form.planName,
              inspectionUserId: this.form.inspectionUserId.toString(),
              inspectionType: this.form.inspectionType,
              planData: this.form.inspectionType == '按天' ? this.form.planData : this.form.planData.toString(),
              status: this.form.status,
            }

            updatePlan(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            let params = {
              planName: this.form.planName,
              inspectionUserId: this.form.inspectionUserId.toString(),
              inspectionType: this.form.inspectionType,
              planData: this.form.inspectionType == '按天' ? this.form.planData : this.form.planData.toString(),
              status: this.form.status,
            }
            addPlan(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.inspectionPlanId || this.ids;
      this.$modal.confirm('是否确认删除药桶编号编号为"' + ids + '"的数据项？').then(function () {
        return delPlan(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('his/barrel/export', {
        ...this.queryParams
      }, `barrel_${new Date().getTime()}.xlsx`)
    },
    getDeviceFun(item) {
      let params = {
        inspectionPlanId: item,
      }
      getDevice(params).then(response => {
        this.getDeviceData = response.rows;
      }
      );
    },
    //点位
    handlePoint(item) {
      this.dynamicTags = []
      this.getPoinList();
      // this.getDeviceFun(item.inspectionPlanId);
      this.dynamicTags = item.inspectionSettings
      this.pointOpen = true;

      this.inspectionPlanIditem = item.inspectionPlanId

    },
    submitpoint() {
      this.pointOpen = false
      let arr = this.dynamicTags.map(item => item.inspectionSettingId)
      let params = {
        inspectionPlanId: this.inspectionPlanIditem,
        inspectionSettingIds: arr
      }
      addIotPlan(params).then((res) => {
        this.$modal.msgSuccess("添加成功");
        this.getList();
      })
    },
    getPoinList() {
      listSetting(this.poinParams).then(response => {
        this.pointlist = response.rows;
        this.poinParams.total = response.total;
      });
    },
    distinct1(arr, key) {
      var newobj = {}, newArr = [];
      for (var i = 0; i < arr.length; i++) {
        var item = arr[i];
        if (!newobj[item[key]]) {
          newobj[item[key]] = newArr.push(item);
        }
      }
      return newArr;
    },
    pointlistChange(e) {
      this.dynamicPoin = e
      let arrData = [... this.dynamicPoin, ...this.dynamicTags]
      let newArr = this.distinct1(arrData, "inspectionSettingId");
      this.dynamicTags = newArr
    },
    handleClose(e) {
      let arr = JSON.parse(JSON.stringify(this.dynamicTags))
      let newArr = arr.filter(item => item.inspectionSettingId != e.inspectionSettingId);
      this.dynamicTags = newArr
    }
  }
};
</script>
<style scoped lang="scss">
.poin_warp {
  padding: 5px 10px;

  .poin_header {
    text-align: center;
  }

  // .poin_center {}
}
</style>
